<template>
	<div class="category-list">
		<lang></lang>
		<curr-app></curr-app>
		<list-title :data="header"></list-title>
		<el-input placeholder="输入关键字进行过滤" v-model="filterText" style="margin-top: 10px"></el-input>
		<div class="tree-title">
			<span>栏目名称</span>
			<span class="content">
				<span style="width: 50px">ID</span>
				<span style="width: 50px">外链</span>
				<span style="width: 60px">类型</span>
				<span style="width: 80px">内容总数</span>
				<span style="width: 80px">预览总数</span>
				<span>显示状态</span>
				<span style="width: 150px">操作</span>
			</span>
		</div>
		<el-tree
		:data="categoryList"
		node-key="catid"
		:default-expand-all="true"
		:expand-on-click-node="false"
		:filter-node-method="filterNode"
		v-loading="loading"
		element-loading-text="拼命加载中"
	    element-loading-spinner="el-icon-loading"
	    element-loading-background="rgba(255, 255, 255, 0.92)"
	    @node-drop="handleDrop"
	    draggable
		:allow-drop="allowDrop"
		ref="tree">
			<span class="custom-tree-node" slot-scope="{ node, data }">
				<span>{{ node.label.name }} | {{ data.alias }}</span>
				<span class="content">
					<span style="width: 50px">
						{{ data.catid }}
					</span>
					<span style="width: 50px">
						<span :class="'el-icon-' + ((data.outside == 1)?'close':'check')"></span>
					</span>
					<span style="width: 60px">
						{{ (data.flag == '1')?'单页':'列表' }}
					</span>
					<span style="width: 80px">
						{{ data.content_count }}
					</span>
					<span style="width: 80px">
						{{ data.preview_count }}
					</span>
					<span>
						<el-switch v-model="data.display" @change="changeDisplay(node.key, data)"></el-switch>
					</span>
					<span style="width: 150px">
						<el-button type='text' size="mini" @click="handleField(node, data)" v-if="auth.union">自定义</el-button>
						<el-button type='text' size="mini" @click="handleEdit(node, data)" style="margin-left: 0px" v-if="auth.editor">编辑</el-button>
						<el-popover
						placement="top"
						width="160"
						v-model="delTip[node.key]" v-if="auth.delete">
							<p class="del-tip"><span class="el-icon-question"></span>确定删除吗？</p>
							<div style="text-align: right; margin: 0">
								<el-button size="mini" type="text" @click="delTip.splice(node.key, 1, false)">取消</el-button>
								<el-button type="primary" size="mini" @click="handleDelete(node.key, data)">确定</el-button>
							</div>
							<el-button type="text" slot="reference" :disabled='submitLock[node.key]'>
								删除 <span class="el-icon-loading" v-if='submitLock[node.key]'></span>
							</el-button>
						</el-popover>
					</span>
				</span>
			</span>
		</el-tree>
		<!-- 设置自定义字段 开始 -->
		<el-dialog :title="dialog.title" :visible.sync="dialog.visible" :close-on-click-modal="false" width="600px">
			<el-select v-model="categoryAttr" filterable placeholder="请选择" style="width: 100%" @change="chooseCategoryAttr">
				<el-option
				v-for="item in categoryAttrList"
				:key="item.id"
				:label="item.attr_name"
				:value="item.id"
				:disabled="checkRelationshipsRepeat(item.id)">
				</el-option>
			</el-select>
			<list-table :list="categoryAttrRelationships" :tableLoading="tableLoading" :footer="false" :sort="true" @setSort="setSort" :appid="$route.query.appid" max-height='310' v-if="dialog.visible">
				<template v-slot:data style="height: 300px">
					<el-table-column prop="attr_name" label="字段名称"></el-table-column>
					<el-table-column label="操作" width="50">
						<template slot-scope="scope">
							<el-button type='text' size="mini" @click="handleDeleteContentCategoryAttrRelationships(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</template>
			</list-table>
			<div slot="footer" class="dialog-footer">
				<el-button @click="synchronous()">同步父栏目</el-button>
				<el-button @click="dialog.visible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm()" :disabled='categoryAttrRelationshipsSubmitLock'>
					确 定 <span class="el-icon-loading" v-if='categoryAttrRelationshipsSubmitLock'></span>
				</el-button>
			</div>
		</el-dialog>
		<!-- 设置自定义字段 结束 -->
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import ListTable from "pc/common/ListTable"
import {changeToBool, judgeAuth} from "static/js/common.js"
import {mapGetters} from 'vuex'
import Lang from "pc/common/Lang"
import CurrApp from "pc/common/CurrApp"

export default {
	inject: ['reload'],
	data() {
		return {
			/*appid*/
			appid: this.$route.query.appid,
			currlang: '',//当前选择的语言
			/*头部数据*/
			header: {
				title: '栏目列表',
				reload: true,
				buttons: [
					{
						title: '添加栏目',
						type: 'primary',
						pathName: 'pc/cms/instance/category/Category',
						auth: false,
						query: {
							appid: this.$route.query.appid,
						},
					}
				]
			},
			auth: {
				editor: false,//编辑
				delete: false,//删除
				changeState: false,//显示状态
				sort: false,//排序
				union: false,//自定义字段关联
			},
			dialog: {
				'title': '设置自定义字段',
				'visible': false,
				'parentid': 0,//用于 同步上级栏目自定义字段
				'catid': 0,
			},
			/*自定义字段列表数据*/
			categoryAttrList: [
				// {
				// 	id: 1,
				// 	attr_name: '',
				// 	attr_type: '',
				// 	state: '',
				// },
			],
			/*弹窗中 选择好的自定义字段*/
			categoryAttr: '',
			loading: true,
			filterText: '',//搜索关键词
			categoryList: [],
			tableLoading: true,
			delTip: [],//刪除提示
			submitLock: [],
			/*自定义字段列表*/
			categoryAttrRelationships: [
				// {
				// 	'id': 0,
				// 	'attr_id': 0,
				// 	'attr_name': '',
				// }
			],
			categoryAttrRelationshipsSubmitLock: false,
		};
	},
	components: {
		ListTitle,
		ListTable,
		Lang,
		CurrApp
	},
	created: function() {
		/*获取当前语言*/
		let lang = this.$localstorage.get('lang');
		this.currlang = lang?lang:'zh'

		/*获取所有栏目数据*/
		this.getCategoryList()
		/*权限判断显示*/
		this.header.buttons[0].auth = (judgeAuth('addContentCategory', this.allMenuList) == undefined)?false:true
		this.auth.editor = (judgeAuth('modifyContentCategory', this.allMenuList) == undefined)?false:true
		this.auth.delete = (judgeAuth('delContentCategory', this.allMenuList) == undefined)?false:true
		this.auth.changeState = (judgeAuth('setContentCategoryDisplay', this.allMenuList) == undefined)?false:true
		this.auth.sort = (judgeAuth('contentCategorySort', this.allMenuList) == undefined)?false:true
		this.auth.union = (judgeAuth('setContentCategoryAttrRelationships', this.allMenuList) == undefined)?false:true
	},
	watch: {
		/*搜索关键词*/
		filterText(val) {
			this.$refs.tree.filter(val);
		},
	},
	methods: {
		/*获取栏目*/
		getCategoryList: function(parentid = 0){
			// this.$baseURL('http://super.ac.comdd')
			// console.log(this.$route.query.app_info_id)
			if(this.$api.contentCategoryList != undefined){
				this.$baseURL(this.$domain.cms)
				this.$get(this.$api.contentCategoryList, {
					'appid': this.appid,
					// 'parentid': parentid,
					'type': 'ele',
					'display': 0,
					'lang': this.currlang
				}).then(res => {
					// console.log(res);
					if(res.data.code == 10007){//后台提示需要登录
						this.$cookie.remove('isLogin');//刪除cookie登录信息
						this.reload();
					}
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.categoryList = res.data.data
						}
						this.tableLoading = false
					}
				})
				.catch(err => {})
				.finally(() => {
					this.loading = false
				}) 
			}
		},
		/*自定义字段*/
		handleField(index, row) {
			// console.log(row.catid)
			this.dialog.visible = !this.dialog.visible
			this.dialog.parentid = row.parentid//把点击的分类父ID放到窗口里面，便于 同步父栏目字段
			this.dialog.catid = row.catid//把点击的分类ID放到窗口里面，便于传输到后台
			this.categoryAttr = ''
			if(this.categoryAttrList.length == 0){
				this.getCategoryAttrList()
			}
			this.getContentCategoryAttrRelationshipsList(row.catid)
		},
		/*编辑栏目*/
		handleEdit(index, row) {
			// console.log(row.catid);
			this.$router.push(
				{
					name: 'pc/cms/instance/category/Category', 
					query: {
						appid: this.appid,
						catid: row.catid,
					}
				}
			)
		},
		/*删除栏目*/
		handleDelete(index, row) {
			// console.log(index)
			if(this.$api.delContentCategory != undefined){
				if(!this.submitLock[index]){
					this.submitLock[index] = true//锁住当前的 删除按钮
					this.delTip.splice(index, 1, false)//提示消失
					/*请求后台删除*/
					this.$baseURL(this.$domain.cms)
					this.$get(this.$api.delContentCategory, {
						'appid': this.appid,
						'catid': row.catid
					}).then(res => {
						if(res.data.code == 10007){//后台提示需要登录
							this.$cookie.remove('isLogin');//刪除cookie登录信息
							this.reload();
						}
						if(res.data.code == 0){
							this.$message({
								showClose: true,
								message: res.data.info,
								type: 'success'
							});
							this.reload();
						}else{
							this.$message({
								showClose: true,
								message: res.data.info,
								type: 'error'
							});
						}
						this.submitLock = []
						this.submitLock[index] = false//释放当前的 删除按钮
					})
					.catch(err => {})
					.finally(() => {}) 
				}
			}
		},
		/*过滤节点*/
		filterNode(value, data) {
			if (!value) return true;
			return data.label.name.indexOf(value) !== -1;
		},
		/*列表中直接修改 是否显示*/
		changeDisplay(index, row){
			if(this.$api.setContentCategoryDisplay != undefined){
				/*请求后台*/
				this.$baseURL(this.$domain.cms)
				this.$post(this.$api.setContentCategoryDisplay, {
					'appid': this.appid,
					'catid': row.catid,
					'display': row.display
				}).then(res => {
					if(res.data.code == 10007){//后台提示需要登录
						this.$cookie.remove('isLogin');//刪除cookie登录信息
						this.reload();
					}
					if(res.data.code == 0){
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'success'
						});
					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}else{
				this.$message({
					showClose: true,
					message: '您没有设置状态的权限',
					type: 'error'
				});
			}
		},
		//拖拽完毕 调用分类排序接口
		handleDrop(draggingNode, dropNode, dropType, ev) {
			if(this.$api.contentCategorySort != undefined){
				// console.log(dropNode.data)
				this.$baseURL(this.$domain.cms)
				this.$post(this.$api.contentCategorySort, {
					'appid': this.appid,
					'sort': draggingNode.data.catid,
					'target': dropNode.data.catid,
					'location': dropType
				}).then(res => {
					if(res.data.code == 10007){//后台提示需要登录
						this.$cookie.remove('isLogin');//刪除cookie登录信息
						this.reload();
					}
					if(res.data.code == 0){
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'success'
						});
					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		//判断拖动是否满足条件
		allowDrop(draggingNode, dropNode, type) {
			if(type !== 'inner' && draggingNode.data.parentid == dropNode.data.parentid){//不能进入内部、必须是同一目录
				return true;
			}
		},
		/*取出列表数据*/
		getCategoryAttrList: function(){
			if(this.$api.categoryAttrList != undefined){
				this.$baseURL(this.$domain.cms)
				let query = this.$route.query
				query.pageSize = 100
				// console.log(query)
				this.$get(this.$api.categoryAttrList, query).then(res => {
					// console.log(res.data.data.list);
					if(res.data.code == 10007){//后台提示需要登录
						this.$cookie.remove('isLogin');//刪除cookie登录信息
						this.reload();
					}
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.categoryAttrList = []
							Object.keys(res.data.data.list).forEach((k) => {
								this.categoryAttrList.push ({
									id: res.data.data.list[k].attr_id,
									attr_name: res.data.data.list[k].attr_name,
									attr_type: res.data.data.list[k].attr_type,
									state: changeToBool(res.data.data.list[k].state),
								});
							})
							this.pagination = res.data.data.pageInfo
						}
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*选择字段*/
		chooseCategoryAttr: function(val){
			/*遍历categoryAttrList，找出选择的字段*/
			let obj = this.categoryAttrList.find((item)=>{
				return item.id === val;
			});
			let getName = obj.attr_name;

			/*categoryAttrRelationships里排重，不重复的就添加*/
			let has = false
			this.categoryAttrRelationships.forEach((item, index) => {
				if(item.attr_id == val){
					has = true
				}
			})

			if(!has){
				this.categoryAttrRelationships.push(
					{
						'id': Math.round(Math.random()*1000000),//主要是为了 table组件中需要，不然拖动后再删除会出问题
						'attr_id': val,
						'attr_name': getName,
					}
				)
			}
		},
		/*删除*/
		handleDeleteContentCategoryAttrRelationships(index, row) {
			// console.log(index + '-' + row.attr_id + '-' + row.attr_name)
			this.categoryAttrRelationships.splice(index, 1);//删除当前行
		},
		/*获取自定义字段关联数据*/
		getContentCategoryAttrRelationshipsList($catid){
			if(this.$api.cmsContentCategoryAttrRelationshipsList != undefined){
				this.tableLoading = true
				this.$baseURL(this.$domain.cms)
				this.$get(this.$api.cmsContentCategoryAttrRelationshipsList, {
					'appid': this.appid,
					'catid': $catid,
				}).then(res => {
					// console.log(res);
					if(res.data.code == 10007){//后台提示需要登录
						this.$cookie.remove('isLogin');//刪除cookie登录信息
						this.reload();
					}
					if(res.data.code === 0){
						this.categoryAttrRelationships = []
						if(res.data.data != undefined){
							// this.categoryList = res.data.data
							Object.keys(res.data.data).forEach((k) => {
								this.categoryAttrRelationships.push(
									{
										'id': res.data.data[k].id,
										'attr_id': res.data.data[k].attr_id,
										'attr_name': res.data.data[k].attrName.attr_name,
									}
								)
							})
						}
						this.tableLoading = false
					}
				})
				.catch(err => {})
				.finally(() => {
					this.tableLoading = false
				}) 
			}
		},
		/*提交自定义字段数据*/
		submitForm() {
			// console.log(this.categoryAttrRelationships)
			if(this.$api.setContentCategoryAttrRelationships != undefined){
				this.$baseURL(this.$domain.cms)
				this.$post(this.$api.setContentCategoryAttrRelationships, {
					'appid': this.appid,
					'unionid': this.dialog.catid,
					'data': this.categoryAttrRelationships
				}).then(res => {
					// if(res.data.code == 10007){//后台提示需要登录
					// 	this.$cookie.remove('isLogin');//刪除cookie登录信息
					// 	this.reload();
					// }
					if(res.data.code == 0){
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'success'
						});
					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*自定义字段关联排序*/
		setSort(newIndex, oldIndex){
			// console.log(newIndex, oldIndex)
			this.categoryAttrRelationships = JSON.parse(JSON.stringify(this.categoryAttrRelationships))
			let oldVal = this.categoryAttrRelationships.splice(oldIndex, 1)[0]
			this.categoryAttrRelationships.splice(newIndex, 0, oldVal)
			// console.log(this.categoryAttrRelationships)
		},
		/*同步父栏目字段*/
		synchronous(){
			// console.log(this.dialog.parentid, 888)
			this.getContentCategoryAttrRelationshipsList(this.dialog.parentid)
		}
	},
	computed: {
		/*验证是否已经选择了，不能再选*/
		checkRelationshipsRepeat(val) {
			return function (val) {
				let has = false
				this.categoryAttrRelationships.find((item) => {
					if(val == item.attr_id){
						has = true
					}
				})
				return (has)
			}
		},
		...mapGetters([
			'allMenuList'
		])
	}
};
</script>

<style lang="stylus" scoped>
.category-list
	.tree-title
		flex: 1
		display: flex
		align-items: center
		justify-content: space-between
		padding: 10px 0
		border-bottom: 1px solid #e9ecf4
		font-size: 12px
		font-weight: bold
		color: #909399
		.content
			span
				width: 100px
				display: inline-block
				margin-right: 5px
			span:last-child
				margin-right: 0
				width: 200px
	.el-tree
		/deep/ .el-tree-node__content
			padding: 18px 0
			border-bottom: 1px solid #e9ecf4
		.custom-tree-node
			flex: 1
			display: flex
			align-items: center
			justify-content: space-between
			font-size: 12px
			.content
				>span
					width: 100px
					display: inline-block
					margin-right: 5px
					// border: 1px solid red
				>span:last-child
					margin-right: 0
					.el-button--small
						padding: 0
				>span.icon-sort-up,span.icon-sort-down
					width: 16px
					margin-right: 0px
					color: $theme-color
</style>